package com.smallkingson.ylib.core.concurrent;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by yorun on 2017/8/15.
 */

public abstract class YLoopRunnable implements Runnable {

  List<Runnable> runnables = Collections.synchronizedList(new LinkedList<Runnable>());
  boolean isStop;
  @Override
  public void run() {
    onPreLoop();
    while (!isStop) {
      runPost();
      loop();
    }
    runPost();
  }

  protected void onPreLoop() {
  }

  public synchronized void stop() {
    isStop = true;
    runnables.clear();
  }
  public void post(Runnable runnable) {
    //if (isStop) {
    //  return;
    //}
    runnables.add(runnable);
  }
  public abstract void loop();

  private synchronized void runPost() {
    while (runnables.size()>0) {
      Runnable runnable = runnables.remove(0);
      runnable.run();
    }
  }
}
